﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;
using MyWeb.Common.Captcha;
using MyWeb.Extensions.ServiceExtensions.Swagger;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SimpleCaptcha;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using static MyWeb.Extensions.ServiceExtensions.Swagger.CustomApiVersion;

namespace MyWeb.Api.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    //[Route("api/[Controller]/[action]")]
    [CustomRoute(ApiVersions.V1)]
    [AllowAnonymous]
    public class FileController : BaseController
    {

        private readonly IWebHostEnvironment _env;
        private readonly SimpleCaptcha.ICaptcha _captcha;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="env"></param>
        /// <param name="captcha"></param>
        public FileController(IWebHostEnvironment env, SimpleCaptcha.ICaptcha captcha)
        {
            _env = env;
            _captcha = captcha;
        }


        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("Upload")]
        public IActionResult FileSave(List<IFormFile> files)
        {
            List<string> filenames = new List<string>();

            var webRootPath = _env.WebRootPath;//图片保存位置


            var physicalPath = $"{webRootPath}/";

            if (!Directory.Exists(physicalPath))
            {
                Directory.CreateDirectory(physicalPath);
            }

            DataSet? ds = null;
            string path = "";
            foreach (var file in files)
            {
                var fileExtension = Path.GetExtension(file.FileName);//获取文件格式，拓展名

                var saveName = $"{Path.GetRandomFileName()}{fileExtension}";
                filenames.Add(saveName);//相对路径

                var fileName = webRootPath + saveName;

                using FileStream fs = System.IO.File.Create(fileName);
                file.CopyTo(fs);
                fs.Flush();

                //获取当前路径
                path = Directory.GetCurrentDirectory() + "\\" + fileName;


            }


            ds = ExcelToDataSet(path, true);
            return new JsonResult(new { IsSuccess = true, Data = Json(ds) });
        }


        /// <summary>
        /// 读取Execl数据到DataTable(DataSet)中
        /// </summary>
        /// <param name="filePath">指定Execl文件路径</param>
        /// <param name="isFirstLineColumnName">设置第一行是否是列名</param>
        /// <returns>返回一个DataTable数据集</returns>
        private static DataSet? ExcelToDataSet(string filePath, bool isFirstLineColumnName)
        {
            DataSet dataSet = new DataSet();
            int startRow = 0;
            try
            {
                using (FileStream fs = System.IO.File.OpenRead(filePath))
                {
                    IWorkbook? workbook = null;
                    // 如果是2007+的Excel版本
                    if (filePath.IndexOf(".xlsx") > 0)
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    // 如果是2003-的Excel版本
                    else if (filePath.IndexOf(".xls") > 0)
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    if (workbook != null)
                    {
                        //循环读取Excel的每个sheet，每个sheet页都转换为一个DataTable，并放在DataSet中
                        for (int p = 0; p < workbook.NumberOfSheets; p++)
                        {
                            ISheet sheet = workbook.GetSheetAt(p);
                            DataTable dataTable = new DataTable();
                            dataTable.TableName = sheet.SheetName;
                            if (sheet != null)
                            {
                                int rowCount = sheet.LastRowNum;//获取总行数
                                if (rowCount > 0)
                                {
                                    IRow firstRow = sheet.GetRow(0);//获取第一行
                                    int cellCount = firstRow.LastCellNum;//获取总列数

                                    //构建datatable的列
                                    if (isFirstLineColumnName)
                                    {
                                        startRow = 1;//如果第一行是列名，则从第二行开始读取
                                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                        {
                                            ICell cell = firstRow.GetCell(i);
                                            if (cell != null)
                                            {
                                                if (cell.StringCellValue != null)
                                                {
                                                    DataColumn column = new DataColumn(cell.StringCellValue);
                                                    dataTable.Columns.Add(column);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                        {
                                            DataColumn column = new DataColumn("column" + (i + 1));
                                            dataTable.Columns.Add(column);
                                        }
                                    }

                                    //填充行
                                    for (int i = startRow; i <= rowCount; ++i)
                                    {
                                        IRow row = sheet.GetRow(i);
                                        if (row == null) continue;

                                        DataRow dataRow = dataTable.NewRow();
                                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                                        {
                                            ICell cell = row.GetCell(j);
                                            if (cell == null)
                                            {
                                                dataRow[j] = "";
                                            }
                                            else
                                            {
                                                //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                                switch (cell.CellType)
                                                {
                                                    case CellType.Blank:
                                                        dataRow[j] = "";
                                                        break;
                                                    case CellType.Numeric:
                                                        short format = cell.CellStyle.DataFormat;
                                                        //对时间格式（2015.12.5、2015/12/5、2015-12-5等）的处理
                                                        if (format == 14 || format == 31 || format == 57 || format == 58)
                                                            dataRow[j] = cell.DateCellValue;
                                                        else
                                                            dataRow[j] = cell.NumericCellValue;
                                                        break;
                                                    case CellType.String:
                                                        dataRow[j] = cell.StringCellValue;
                                                        break;
                                                }
                                            }
                                        }
                                        dataTable.Rows.Add(dataRow);
                                    }
                                }
                            }
                            dataSet.Tables.Add(dataTable);
                        }

                    }
                }
                return dataSet;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Ks_Import(IFormFile file)
        {
            try
            {
                var stream = file.OpenReadStream();//获取文件内容
                var fileType = Path.GetExtension(file.FileName);//获取文件后碳带.
                DataTable dt = new DataTable();
                ISheet? sheet = null;
                IWorkbook? workbook = null;

                #region 判断excel版本
                // 2007以上版本excel
                if (fileType == ".xlsx")
                {
                    workbook = new XSSFWorkbook(stream);
                }
                // 2007以下版本exceL
                else if (fileType == ".xls")
                {
                    workbook = new HSSFWorkbook(stream);
                }
                else
                {
                    throw new Exception("传入的不是Excel文件! ");
                }
                #endregion

                sheet = workbook.GetSheetAt(0);//取第1个工作表
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);//首行
                    int cellCount = firstRow.LastCellNum;//列总数
                    for (int i = firstRow.FirstCellNum; i < cellCount; i++)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string cellValue = cell.StringCellValue.Trim();
                            if (!string.IsNullOrEmpty(cellValue))
                            {
                                DataColumn dataColumn = new DataColumn(cellValue);
                                dt.Columns.Add(dataColumn);
                            }
                        }
                    }

                    //var Data = new List<ModelGraduateCheckImport>();
                    //var modelGraduateCheckImport = new ModelGraduateCheckImport();

                    //遍历行
                    for (int j = sheet.FirstRowNum + 1; j <= sheet.LastRowNum; j++)
                    {
                        IRow row = sheet.GetRow(j);

                        if (row == null || row.FirstCellNum < 0)//编号
                        {
                            continue;
                        }

                        DataRow dr = dt.NewRow();
                        //遍历列
                        for (int i = row.FirstCellNum; i < cellCount; i++)
                        {
                            ICell celLData = row.GetCell(i);
                            ICell cell = firstRow.GetCell(i);

                            if (celLData == null)
                            {
                                dr[cell.StringCellValue.Trim()] = null;
                                continue;
                            }

                            if (celLData.CellType == CellType.String)
                            {
                                dr[cell.StringCellValue.Trim()] = celLData.StringCellValue.Trim();
                            }
                            if (celLData.CellType == CellType.Numeric)
                            {
                                dr[cell.StringCellValue.Trim()] = celLData.NumericCellValue;
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                }
                else
                {
                    throw new Exception("没有获取到Excel中的数据表!");
                }
                return Json(new { code = 0, msg = "导入成功", data = JsonConvert.SerializeObject(dt) });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    code = -1,
                    msg = "导入出错" + ex.Message,
                });
            }
        }



        /// <summary>
        /// 下载文件【.NET Core 不能用】
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage DownloadFile()
        {
            string fileName = "aa.xlsx";//文件的服务器地址
            //string filePath = HttpContext.Current.Server.HMapPath("~/ ") + "Web\\wordtemp\\" + "word.docx";

            string filePath = "C:\\FtpSite\\aa.xlsx";
            FileStream stream = new FileStream(filePath, FileMode.Open);
            HttpResponseMessage Response = new HttpResponseMessage(HttpStatusCode.OK);
            Response.Content = new StreamContent(stream);
            Response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            Response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = HttpUtility.UrlEncode(fileName)
            };
            Response.Headers.Add("Access-Control-Expose-Headers", "FileName");
            Response.Headers.Add("FileName", HttpUtility.UrlEncode(fileName));
            return Response;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet("DownloadImportTemp")]
        public IActionResult DownloadImportTemp()
        {
            string filePath = "C:\\FtpSite\\aa.xlsx";
            //string filePath = AppContext.BaseDirectory + "/TempFile/SutdentInfoTemp.xlsx";
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
            return File(fileStream, "application/octet-stream", "学生导入模板.xlsx");
        }


        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Captcha")]
        public IActionResult Captcha(string id)
        {
            var info = _captcha.Generate(id);
            var stream = new MemoryStream(info.CaptchaByteData);
            return File(stream, "image/png");
        }
        /// <summary>
        /// 验证验证码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet("Validate")]
        public IActionResult Validate(string id, string code)
        {
            var result = _captcha.Validate(id, code);
            return Json(new { success = result });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> CaptchaTest()
        {
            Common.Captcha.ICaptcha captcha = new Captcha();
            var code = await captcha.GenerateRandomCaptchaAsync(4);
            var result = await captcha.GenerateCaptchaImageAsync(code);
            return base.File(fileContents: result.CaptchaMemoryStream.ToArray(), "image/png");
        }
    }
}
